package com.hntxk.cqzd.diagnosis.service.impl;


import com.hntxk.core.framework.model.OperModel;
import com.hntxk.core.framework.model.ResponseModel;
import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.ModelEntityUtil;
import com.hntxk.core.util.NumberUtil;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisInfo;
import com.hntxk.cqzd.diacrisis.service.DiacrisisInfoService;
import com.hntxk.cqzd.diagnosis.bizcheck.DiagnosisInfoBizCheck;
import com.hntxk.cqzd.diagnosis.model.DiagnosisFruit;
import com.hntxk.cqzd.diagnosis.model.DiagnosisInfo;
import com.hntxk.cqzd.diagnosis.service.DiagnosisInfoService;
import com.hntxk.sp.log.model.ActionTypeEnum;
import com.hntxk.sp.util.LogRecordUtil;
import com.hntxk.sp.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author
 */
@Service
public class DiagnosisInfoServiceImpl extends BaseServiceImpl<DiagnosisInfo> implements DiagnosisInfoService {

    public static String  MAPPER_NAMESPACE = "com.hntxk.cqzd.diagnosis.mapper.DiagnosisInfoMapper.";


    private final DiacrisisInfoService diacrisisService;

    @Autowired
    public DiagnosisInfoServiceImpl(@Qualifier("diacInfoService") DiacrisisInfoService diacrisisService) {
        super(MAPPER_NAMESPACE);
        this.diacrisisService = diacrisisService;
    }

    @Override
    public List<DiagnosisInfo> query(DiagnosisInfo model) {

        ModelEntityUtil.setEmptyStrToNull(model, true);
        List<DiagnosisInfo> result = getDasTemplate().selectList(MAPPER_NAMESPACE+"query",model);
        //查询每项结果的检验结果
        for (DiagnosisInfo info : result) {
            info.setDiagnosisFruit(getDasTemplate().selectList(MAPPER_NAMESPACE+"queryFruit",info));
        }
        return result;
    }

    /**
     * 删除診斷结果
     * @param diacrisisId 诊断记录ID
     */
    public int deleteInfo(long diacrisisId) {
        DiagnosisInfo info = new DiagnosisInfo();
        info.setDiacrisisId(diacrisisId);
        return delete(MAPPER_NAMESPACE+"delete",info);
    }


    /**
     * 保存诊断结果
     * 一条诊断记录对应一次诊断结果，一次诊断结果包含一到多条诊断结果记录
     * 处理思路：
     * step1.删除当前诊断记录已有的所有诊断结果
     * step2.再将infoList逐条新增到数据库
     *
     * @param infoList 诊断结果list
     * @return 失败信息
     */
    @Override
    public ResultModel<DiagnosisInfo> save(List<DiagnosisInfo> infoList) {

        if (infoList.size()==0){
            return new ResultModel<>(infoList);
        }
        //从第一条结果中取诊断记录ID
        Long diacrisisId = infoList.get(0).getDiacrisisId();
        TblDiacrisisInfo diacrisisInfo = diacrisisService.getById(diacrisisId);
        if (null == diacrisisInfo || null == diacrisisInfo.getPatientName()){
            return new ResultModel<>("更新失败,提供的记录ID有误.");
        }
        //保存诊断结果的业务验证
        DiagnosisInfoBizCheck bizCheck = new DiagnosisInfoBizCheck(this);
        for (DiagnosisInfo info : infoList) {
            info.setCreateUserId(LoginUserUtil.getLoginOperatorIdLong());
            info.setCreateUserName(LoginUserUtil.getLoginUserName());
            info.setCreateTime(new Date());
            //开始验证，主要验证必填项
            if (NumberUtil.isNotNull(info.getDiagnosisId())) {
                bizCheck.updatable(info);
            } else {
                bizCheck.addable(info);
            }
            if (bizCheck.hasError()) {
                return bizCheck.getErrorResultModel();
            }
        }

        //删除诊断记录的诊断结果的检验结果
        deleteFruit(diacrisisId);
        //删除之前诊断记录之前的的诊断结果
        deleteInfo(diacrisisId);
        for (DiagnosisInfo info : infoList) {
            if (null == info.getInspectionTime()){
                //页面没有的检测时间的，认为是不需要保存的记录
                continue;
            }
            if (NumberUtil.isNull(info.getDiagnosisId())) {
                getPrimaryKey(info);
            }
            super.insert(MAPPER_NAMESPACE+"insert",info);
            //保存诊断结果的检验结果
            for (DiagnosisFruit fruit : info.getDiagnosisFruit()) {
                getPrimaryKey(fruit);
                fruit.setDiagnosisId(info.getDiagnosisId());
                super.insert(MAPPER_NAMESPACE+"insertFruit",fruit);
            }
        }
        //写操作日志
       LogRecordUtil.addLog(diacrisisInfo, ActionTypeEnum.UPDATE,"更新了["+diacrisisInfo.getOutpatientNo()+"]["+diacrisisInfo.getPatientName()+"]的诊断结果");
        return new ResultModel<>(infoList);
    }

    @Override
    public String delete(String diacrisisId, OperModel operInfo) {
        long id = 0;
        try {
            id = Long.parseLong(diacrisisId);
        } catch (NumberFormatException e) {
            return "删除失败,提供的记录ID格式不正确.";
        }

        TblDiacrisisInfo diacrisisInfo = diacrisisService.getById(id);
        if (null == diacrisisInfo || null == diacrisisInfo.getPatientName()){
            return "删除失败,提供的记录ID有误.";
        }
        //删除诊断记录之前的的检验结果
        deleteFruit(id);
        int count = deleteInfo(id);
        LogRecordUtil.addLog(diacrisisInfo, ActionTypeEnum.UPDATE,"删除了["+diacrisisInfo.getOutpatientNo()+"]["+diacrisisInfo.getPatientName()+"]的诊断结果");
       // ActionLogManager.getInstance().addLog(new ActionLog(TblDiacrisisInfo.class,diacrisisId, ActionType.DELETE,"删除了["+diacrisisInfo.getOutpatientNo()+"]["+diacrisisInfo.getPatientName()+"]的诊断结果"));
        return count>0 ? null : "删除失败";
    }

    /**
     * 删除诊断记录的诊断结果的检验结果
     * @param diacrisisId 诊断记录ID
     */
    private int deleteFruit(long diacrisisId){
        DiagnosisInfo info = new DiagnosisInfo();
        info.setDiacrisisId(diacrisisId);
        return delete(MAPPER_NAMESPACE+"deleteFruit",info);
    }

    @Override
    public DiacrisisInfoService getDiacrisisService() {
        return diacrisisService;
    }

    @Override
    public ResponseModel listDiacrisis(TblDiacrisisInfo model) {

        model.getPagination().setPageSize(6);
        ModelEntityUtil.forceEmptyStrToNull(model,true);
        //已经登记过诊断结果的诊断记录
        List<?> histories = query(MAPPER_NAMESPACE + "queryHistories", model);
        //未登记过诊断结果的诊断记录
        List<?> todoList = query(MAPPER_NAMESPACE + "queryTodoList", model);

        ResponseModel jsonObject = ResponseModel.empty();
        jsonObject.put("histories",histories);
        jsonObject.put("todoList",todoList);
        jsonObject.put("status","1");
        return jsonObject;
    };
}
